package com.lh.jianzhioffer;


/**
 * @author: linghao
 * @since: 2023/2/12
 *
 * 输入两棵二叉树A和B，判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
 *
 * B是A的子结构， 即 A中有出现和B相同的结构和节点值
 */
public class 树的子结构26 {

    //递归遍历A 与 B进行比较
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        return (A != null && B != null) && (recur(A,B) || isSubStructure(A.left,B) || isSubStructure(A.right,B));
    }

    private boolean recur(TreeNode a, TreeNode b) {
        if(b == null)return true;  //b树递归完，说明完全匹配
        if(a == null || a.val != b.val)return false; //A树遍历完了 B树任然没完，或者节点不相等
        return recur(a.left,b.left) && recur(a.right,b.right);
    }


    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
}
